package com.z_talk.server.localization;

import com.z_talk.core.model.UserInfo;
import com.z_talk.core.util.FileUtil;
import com.z_talk.server.config.PropertiesUtil;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class TalkLocalzation {

    public static String loadWorldTalk()  {
        try {
            String filePath = PropertiesUtil.configProp.getProperty("worldTalkFilePath");
            String fileName = PropertiesUtil.configProp.getProperty("worldTalkFile");
            File file =  FileUtil.createFile(filePath+fileName);
            Path fpath= Paths.get(file.getPath());
            String talk = new String(Files.readAllBytes(fpath));
            return talk;
        }catch (EOFException e) {
            return new String();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean saveWorldTalk(String talk){
        try {
            String filePath = PropertiesUtil.configProp.getProperty("worldTalkFilePath");
            String fileName = PropertiesUtil.configProp.getProperty("worldTalkFile");
            File file =   FileUtil.createFile(filePath+fileName);
            Files.write(Paths.get(file.getPath()),talk.getBytes(), StandardOpenOption.APPEND);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String loadPrivateTalk(UserInfo from,UserInfo to)  {
        try {
            String filePath = PropertiesUtil.configProp.getProperty("privateTalkFilePath");
            String fileName = from.getNickName()+"_"+to.getNickName()+".db";
            File file =  FileUtil.createFile(filePath+fileName);
            Path fpath= Paths.get(file.getPath());
            String talk = new String(Files.readAllBytes(fpath));
            return talk;
        }catch (EOFException e) {
            return new String();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean savePrivateTalk(UserInfo from,UserInfo to,String talk){
        try {
            String filePath = PropertiesUtil.configProp.getProperty("privateTalkFilePath");
            String fileName = from.getNickName()+"_"+to.getNickName()+".db";
            File file = FileUtil.createFile(filePath+fileName);
            Files.write(Paths.get(file.getPath()),talk.getBytes(), StandardOpenOption.APPEND);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
